package com.ticket.filter;


import com.ticket.common.time.CommonFunction;
import com.ticket.common.string.StringUtil;

import com.ticket.common.token.TokenUtil;

//import com.yh.db.entity.TblLogInfo;

import com.ticket.db.entity.TblUserInfo;
import com.ticket.common.rescode.Rescode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

public abstract class BaseAuthFilter implements Filter  {
	//@Autowired
	//TblLogInfoMapper logInfoDao;
	public boolean checkFlag=true;//验签、验登录开关

//	private static Logger logger =Logger.getLogger(BaseAuthFilter.class);

	private static Logger logger = LoggerFactory.getLogger(BaseAuthFilter.class);


	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}
	@Override
	public void destroy() {

	}
	@Override
	public void doFilter(ServletRequest  servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String currentURL = request.getRequestURI();
		String xToken=request.getHeader("X-Token");//即用户的id（非userId）
		String userToken=request.getHeader("User-Token");
		Map<String, String[]> map=request.getParameterMap();
		logger.info("xToken"+xToken+",userToken="+userToken+",用户请求地址："+currentURL);
		String callType=request.getHeader("Call-Type");
		logger.info("call type："+callType);
		if(this.passUrl(currentURL)||"Feign".equals(callType)){//访问免登录服务
			filterChain.doFilter(request, response);
//			response.setHeader("passurl", "yes");//设置了没什么用，还是在各自的controller中自行设置
		}else if(StringUtil.isEmpty(xToken)){//无登录id信息且不是免登录服务，
			logger.info("============没有用户登录信息=============");
			if(checkFlag){
				this.illegalAccess(response);
				System.out.println("失败");
				return ;
			}else{//默认登录用户，一般开发时使用
//				TblUserInfo userInfo=this.getUserInfo("afc1fc978dfb486c8cd3eb94ec87cc2c");
//				System.out.println(userInfo);
//				request.setAttribute("userInfo", userInfo);
//				checkFlag=true;
			}
		}else{
			//验证token
			if(checkFlag){//开启验签开关
				if(!TokenUtil.checkToken(xToken, userToken)){
					logger.error("接口验签失败");
					this.writeLog(currentURL, xToken,"接口验签失败");
					this.illegalAccess(response);
					return;
				}
			}
			//校验通过，获取个人信息
			TblUserInfo userInfo=this.getUserInfo(xToken);
			request.setAttribute("userInfo", userInfo);
			this.writeLog(currentURL, userInfo.getUuid(),"");
			filterChain.doFilter(request, response);
		}
	}

	public boolean passUrl(String currentURL){
		String[] passurls = new String[]{
				"/user/login","/weChat/weChatOpen","/User/login",
		};
		if( Arrays.asList(passurls).contains(currentURL)){
			return true;
		}
		String[] screenUrls = new String[] {
				"/ump/bigscreen",
				"/ump/subscreen"
		};
		logger.info("checking screenUrls");
		// 对大屏/子页面接口做单独跳过处理
		for (String pattern: screenUrls) {
			logger.info(currentURL);
			if (currentURL.startsWith(pattern)) {
				logger.info("passed");
				return true;
			}
		}
		return false;
	}
	public void illegalAccess(HttpServletResponse response){
		try {
			response.getWriter().print(Rescode.IllegalAccess);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			logger.info("",e);
		}//非法访问错误码
	}
	public void writeLog(String url,String userId,String message){
//		TblLogInfo loginfo = new TblLogInfo();
//		loginfo.setId(StringUtil.getUUID());
//		loginfo.setUrl(url);
//		loginfo.setOprid(userId);
//		loginfo.setOprdt(CommonFunction.getLocalTime14());
//		loginfo.setResultDesc(message);
		//logInfoDao.insert(loginfo);
	}
	public abstract TblUserInfo getUserInfo(String userToken);


}
